<template>
    <el-card>
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索">
                <el-input v-model="keyword" placeholder="请您输入搜索职位关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="search" :disabled="keyword ? false : true">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin:10px 0px;">
        <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
        <el-table border style="margin:10px 0px;" :data="allRole">
            <el-table-column type="index" align="center" label="#"></el-table-column>
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <el-table-column prop="roleName" label="职位名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="280px" align="center">
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                    <el-popconfirm :title="`您确定要删除${row.roleName}吗？`" width="260px" @confirm="removeRole(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination @size-change="sizeChange" @current-change="getHasRole" v-model:current-page="pageNo"
            v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]" :background="true"
            layout=" prev, pager, next, jumper,->, sizes,total" :total="total" />
    </el-card>
    <!-- 添加职位与更新职位的结构 -->
    <el-dialog v-model="dialogVisite" :title="RoleParams.id ? '更新职位' : '添加职位'">
        <el-form :model="RoleParams" :rules="rules" ref="form">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请您输入职位名称" v-model="RoleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" size="default" @click="dialogVisite = false">取消</el-button>
            <el-button type="primary" size="default" @click="save">确定</el-button>
        </template>
    </el-dialog>
    <!-- 抽屉结构 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>分配菜单与按钮的权限</h4>
        </template>
        <template #default>
            <!-- 树形控件 -->
            <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="selectArr" :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="handler">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqRomoveRole, reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermissstion } from '@/api/acl/role/index'
import useLayOutSettingStore from '@/store/modules/setting';
import { ElMessage } from 'element-plus';
const settingStore = useLayOutSettingStore()
let pageNo = ref(0)
let pageSize = ref(10)
let total = ref(0)
let form = ref()
let keyword = ref('')
// 存储全部已有的角色
let allRole = ref([])
// 控制抽屉显示与隐藏
let drawer = ref(false)
// 控制对话框的显示与隐藏
let dialogVisite = ref(false)
// 收集新增岗位的数据
let RoleParams = reactive<any>({
    roleName: ''
})
// 定义数组存储用户权限的数据
let menuArr = ref([])
// 定义一个数组过滤用户权限的数据
let selectArr = ref<any>([])
let tree = ref()
onMounted(() => {
    getHasRole()
})
// 获取全部角色的方法
const getHasRole = async (pager = 1) => {
    pageNo.value = pager
    let result = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
    if (result.code == 200) {
        total.value = result.data.total
        allRole.value = result.data.records
    }
}
// 分页器下拉菜单的回调
const sizeChange = () => {
    getHasRole()
}
// 搜索按钮的回调
const search = () => {
    getHasRole()
    keyword.value = ''
}
// 重置按钮的回调
const reset = () => {
    settingStore.refsh = !settingStore.refsh
}
// 添加职位按钮的回调
const addRole = () => {
    dialogVisite.value = true
    Object.assign(RoleParams, {
        roleName: '',
        id: 0
    })
    nextTick(() => {
        form.value.clearValidate('roleName')
    })
}
// 更新职位按钮的回调
const updateRole = (row: any) => {
    dialogVisite.value = true
    Object.assign(RoleParams, row)
    nextTick(() => {
        form.value.clearValidate('roleName')
    })
}
// 自定义表单校验规则
const validatorRoleName = (_: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack()
    } else {
        callBack(new Error('职位名称至少两位'))
    }
}
// 表单校验的规则对象
const rules = {
    roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
// 对话框确定按钮的回调
const save = async () => {
    await form.value.validate()
    let result = await reqAddOrUpdateRole(RoleParams)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: RoleParams.id ? '更新成功' : '添加成功' })
        dialogVisite.value = false
        getHasRole(RoleParams.id ? pageNo.value : 1)
    }
}
// 分配权限按钮的回调
const setPermisstion = async (row: any) => {
    drawer.value = true
    Object.assign(RoleParams, row)
    let result = await reqAllMenuList(RoleParams.id)
    if (result.code == 200) {
        menuArr.value = result.data
        selectArr.value = filterSelectArr(menuArr.value, [])
    }
}
// 树形控件数据
const defaultProps = {
    children: 'children',
    label: 'name'
}
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select && item.level == 4) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }
    });
    return initArr
}
// 抽屉确定按钮的回调
const handler = async () => {
    // 职位的id
    const roleId = RoleParams.id
    // 选中节点的id
    let arr = tree.value.getCheckedKeys()
    // 半选的id
    let arr1 = tree.value.getHalfCheckedKeys()
    let permissionId = arr.concat(arr1)
    let result = await reqSetPermissstion(roleId, permissionId)
    if (result.code == 200) {

        drawer.value = false
        // window.location.reload()
        ElMessage({ type: 'success', message: '分配权限成功' })
    }
}
// 删除已有的职位的回调
const removeRole = async (id: any) => {
    let result = await reqRomoveRole(id)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
</script>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
}
</style>